<template>
  <div class="pd30 produceFactory">
    <div class="panelWrap">
      <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
        <div>库存管理</div>
        <!-- <el-button class="addBtn fw defaultbtn"  type="primary">添加</el-button> -->
      </div>
      <div class="con">
        <div class="con-row flex flexac pl search-box">
          <div class="flex">
            <!-- <el-select v-model="queryParam.companyName"  class="isWechat-select coInput m-r-15" placeholder="机构名称">
              <el-option label="机构名称" value="0" />
            </el-select> -->
            <el-input clearable v-model="queryParam.equipmentName" class="query-input m-r-15" placeholder="BOM名称" @input="handleSearch" />
            <el-date-picker class="query-input m-r-15" v-model="queryParam.endDate" value-format="yyyy-MM-dd" :picker-options="pickerOption" clearable type="date" placeholder="结束日期">
            </el-date-picker>
            <!-- <el-select v-model="outState"  class="isWechat-select coInput" placeholder="出库状态">
              <el-option v-for="(item,index) in outStateList" :key="index" :label="item" :value="index" />
            </el-select> -->
          </div>
          <div class="groupbtn flex">
            <el-button class="flex flexac fs14" size="small" type="warning" @click="queryStock"><i class="co-i" /><span class="search1">查 询</span></el-button>
            <el-button class="flexcenter co-empty m-l-25" type="info" @click="handleEmptySearch"><i class="iconfont icon-qingkong" />清 空</el-button>
            <el-button class="defaultbtn" type="primary" @click="stockEnter"><i class="el-icon-circle-plus-outline" />入库</el-button>
            <el-button class="defaultbtn" type="primary" @click="stockOut"><i class="el-icon-remove-outline" />销售出库</el-button>
            <el-button class="defaultbtn" type="primary" @click="stockOutReturn"><i class="el-icon-remove-outline" />退货出库</el-button>
            <el-button class="defaultbtn" type="primary" @click="stockOutInstall"><i class="el-icon-remove-outline" />安装出库</el-button>
            <el-button class="defaultbtn" type="primary" @click="handleExportExcel"><i class="iconfont icon-wenjiandaochu" />导出</el-button>
          </div>
        </div>

        <el-table id="dataList" ref="dataList" class="con-table" type="expand" :data="dataList.slice((paging.currentPage - 1) * paging.pageSize, paging.currentPage * paging.pageSize)" @select="handleCheck" @select-all="handleCheck" @selection-change="handleCheckChange">
          <el-table-column width="50" type="selection" label="全选" />

          <el-table-column width="100" align="center" label="仓库ID">
            <template slot-scope="scope">
              <span>{{ scope.row.whId }}</span>
            </template>
          </el-table-column>

          <el-table-column width="100" align="center" label="库存量">
            <template slot-scope="scope">
              <span>{{ scope.row.weight }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="设备编号">
            <template slot-scope="scope">
              <span>{{ scope.row.deviceNo }}</span>
            </template>
          </el-table-column>

          <el-table-column label="物理序列号" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.serialNo }}</span>
            </template>
          </el-table-column>

          <el-table-column label="购入时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.buyDate }}</span>
            </template>
          </el-table-column>

          <el-table-column label="含税单价" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.taxPrice }}</span>
            </template>
          </el-table-column>

          <!-- <el-table-column  label="库存状态" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.status }}</span>
            </template>
          </el-table-column> -->

          <el-table-column label="物料编码" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.itemCode }}</span>
            </template>
          </el-table-column>

          <el-table-column label="BOM名称" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.equipmentName }}</span>
            </template>
          </el-table-column>

          <el-table-column label="BOM厂家" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.companyName }}</span>
            </template>
          </el-table-column>

          <el-table-column label="所属机构" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.orgNameSimple }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="name" align="center" label="操作">
            <template slot-scope="scope">
              <el-button class="defaultbtn" type="primary" @click="handleEdit(scope.$index, scope.row)">
                <i />模块配置
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="paginationWrap flex" :current-page="paging.currentPage" :page-sizes="paging.pageSizeArr" :page-size="paging.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="paging.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-dialog @closed="handleCloseMoudle" class="moudleDialog" :visible="moudleDialog">
      <el-form v-model="moudleForm">
        <el-form-item label="选择模块">
          <el-checkbox-group v-model="moudleForm.moudleIdList">
            <el-checkbox v-for="item in moudleIdList" :key="item.id" :label="item.id" name="type">{{item.moudleKey}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="选择模块" prop="ftpId" class="checkInput flex flexac m-b-20">
          <el-input v-model="moudleForm.ftpId" class="com-input" placeholder="请选择ftpID" readonly />
          <div>
            <el-button type="warning" class=" m-l-20 iconfont icon-xuanze" @click="handleSelect(6)">选择ftpID</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="moudleDialog = false">取 消</el-button>
        <el-button type="primary" @click="addMoudle">确 定</el-button>
      </div>
    </el-dialog>
    <ProductEdit :outType="outType" :list="dataList" v-model="visible" :data="editSystem" :is-edit="isEdit" @handleRefresh="handleRefresh" @handleCloseDialog="handleCloseDialog" />
    <pubSelect :stockType="2" v-model="coSelectVisible" :select-type="selectType" :title="selectTitle" @update="handleSelectUpdate" />
  </div>
</template>

<script>
import pubSelect from '@/components/pubSelect/index'
import ProductEdit from './dialog'
import { fetchStockList, setScreen, fetchMoudleList, stockDetail } from '@/api/operation/BOM/opStock'
import { formatDateTime } from '@/utils/toolclass'
import { showNotice } from '@/utils/toolclass'

export default {
  name: 'stock',
  components: {
    ProductEdit,
    pubSelect
  },
  props: {},
  data() {
    return {
      stockDetail: {},
      selectTitle: '',
      selectType: 0,
      coSelectVisible: false,
      moudleIdList: [],
      moudleForm: {
        ftpId: '',
        moudleIdList: [],
        stockId: ''
      },
      moudleDialog: false,
      outType: 1,
      userInfo: {},
      outState: '',
      outStateList: ['采购入库', '销售出库', '退货入库', '退货出库', '维修入库', '维修出库', '报废出库', '安装出库'], //出库状态
      pickerOption: {
        //设置日期禁用状态
        disabledDate(date) {
          return date.getTime() > Date.now();
        }
      },
      delPro: '',
      paging: {
        currentPage: 1,
        pageSize: 10,
        pageSizeArr: [10, 20, 50, 100],
        total: 400
      },

      dataList: [],
      queryParam: {
        companyName: '',
        equipmentName: '',
        endDate: ''
      },
      visible: false,
      editSystem: {},
      isEdit: false,
      refresh: false,
      url: require('@/assets/error.png'),
      seniorSet: {
        'field': false,
        'sortable': false
      },
      tablehead: [
        {
          index: 0,
          prop: 'name',
          label: '系统名',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 1,
          prop: 'id',
          label: '简称',
          sortable: false,
          fixed: true,
          isShow: true
        }
      ]

    }
  },
  computed: {},
  watch: {},
  created() {
    this.getStockList()
  },
  mounted() {
    this.userInfo = JSON.parse(this.$storage.get('userInfo'))
    this.$storage.set('upUrl', JSON.stringify({ 'path': '/operation/ERP/stock/index' }))
  },
  methods: {
    // 获取库存详情
    async getStockDetail(id) {
      await stockDetail(id).then(res => {
        if (res.code === '000000') {
          this.stockDetail = res.data
        } else {
          showNotice('warning', '提示', res.msg)
        }
      })
    },
    // 配置模块弹窗关闭
    handleCloseMoudle() {
      this.moudleForm = {
        ftpId: '',
        moudleIdList: [],
        stockId: ''
      }
    },
    //获取模块配置列表
    getMoudleList() {
      const params = {
        'pageIndex': 1,
        'pageSize': 99
      }
      fetchMoudleList(params).then(res => {
        if (res.code === '000000') {
          this.moudleIdList = res.data;
        } else {
          showNotice('warning', '提示', res.msg)
        }
      })
    },
    // 信息更新回调
    handleSelectUpdate(row) {
      switch (this.selectType) {
        case 6:
          this.moudleForm.ftpId = row.id
          break
        default:
          break
      }
      // this.handleValueChange(row.id)
    },
    handleSelect(type) {
      this.coSelectVisible = true
      this.selectType = type
      switch (type) {
        case 6:
          this.selectTitle = 'ftpId'
          break
        default:
          break
      }
    },
    addMoudle() {
      setScreen(this.moudleForm).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '模块配置成功')
          this.moudleDialog = false
        } else {
          showNotice('warning', '提示', res.msg)
        }
      })
    },
    //导出excel
    handleExportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        const tHeader = ['仓库ID', '库存量', '设备编号', '物理序列号', '购入时间', '含税单价', '物料编码', 'BOM名称', 'BOM厂家', '所属机构']
        const filterVal = ['whId', 'weight', 'deviceNo', 'serialNo', 'buyDate', 'taxPrice', 'itemCode', 'equipmentName', 'companyName', 'orgNameSimple']
        const data = this.formatJson(filterVal, this.dataList)
        export_json_to_excel(tHeader, data, '库存管理表(' + formatDateTime().ymd) + ')'
      })
    },
    //入库
    stockEnter() {
      this.$router.push({ path: '../stockEnter/index' })
    },
    //销售出库
    stockOut() {
      if (this.delPro) {
        this.outType = 1
        this.visible = true
        this.isEdit = false
        this.editSystem = {
          orgId: this.userInfo.currentOrgId,
          entId: '',
          id: '',
          outDate: '',
          serialNo: this.delPro.serialNo,
          saleContractId: '',
          stockId: this.delPro.id,
          taxPrice: '',
          taxRate: '0.16',
          userId: this.userInfo.userId,
          version: this.delPro.version
        }
      } else {
        showNotice('warning', '提示', '请选择设备!')
      }

    },
    //退货出库
    stockOutReturn() {
      if (this.delPro) {
        this.outType = 2
        this.visible = true
        this.isEdit = false
        this.editSystem = {
          orgId: this.userInfo.currentOrgId,
          entId: '',
          id: '',
          outDate: '',
          saleContractId: '',
          stockId: this.delPro.id,
          taxPrice: '',
          taxRate: '0.16',
          userId: this.userInfo.userId,
          version: this.delPro.version
        }
      } else {
        showNotice('warning', '提示', '请选择设备!')
      }
    },
    // 安装出库
    async stockOutInstall() {
      if (this.delPro) {
        await this.getStockDetail(this.delPro.id)
        if (this.stockDetail.moudleList.length <= 0) {
          showNotice('warning', '提示', '请先配置模块!')
        } else {
          this.outType = 3
          this.visible = true
          this.isEdit = false
          this.editSystem = {
            orgId: this.userInfo.currentOrgId,
            elevatorId: '',
            entId: '',
            outDate: '',
            stockId: this.delPro.id,
            userId: this.userInfo.userId,
          }
        }
      } else {
        showNotice('warning', '提示', '请选择设备!')
      }
    },
    handleCheck(selection, row) {
      this.$refs.dataList.clearSelection()
      if (selection.length === 0) { // 判断selection是否有值存在
        this.delPro = '';
        return
      }
      if (row) {
        this.selectioned = row
        this.row = row
        this.delPro = row
        this.$refs.dataList.toggleRowSelection(row, true)
      }
    },
    handleCheckChange(row) {
      if (row.length === 0) {
        this.delPro = ''
        this.selectioned = null
      }
    },
    handleDetail(index, row) {
      this.$router.push({
        name: 'system-detail',
        params: { index, row }
      })
    },
    handleSenior(type) {
      if (type === 'field') {
        this.seniorSet.field = !this.seniorSet.field
      }
      if (type === 'sortable') {
        this.seniorSet.sortable = !this.seniorSet.sortable
      }
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleRefresh() {
      this.refresh = true
      this.getStockList()
      setTimeout(() => {
        this.refresh = false
      }, 1200)
    },
    queryStock() {
      const params = {
        endDate: this.queryParam.endDate,
        equipmentName: this.queryParam.equipmentName,
        pageIndex: this.paging.currentPage,
        pageSize: this.paging.pageSize
      }
      fetchStockList(params).then(res => {
        this.dataList = res.data.filter(item => {
          if (item.equipmentName.toLowerCase().indexOf(this.queryParam.equipmentName) > -1) {
            return this.dataList.push(item)
          }
        })
        this.handleSearch(this.dataList)
      })
    },
    handleSearch(name) {
      if (this.queryParam.name === '') {
        this.getStockList()
      }
    },
    //获取库存列表
    getStockList() {
      const params = {
        pageIndex: this.paging.currentPage,
        pageSize: this.paging.pageSize
      }
      fetchStockList(params).then((res) => {
        if (res.code === '000000') {
          this.dataList = res.data
          const i = res.data.map((item, i) => i)
          this.paging.total = i.length
        }
      })
    },
    //清空搜索栏
    handleEmptySearch() {
      this.queryParam.equipmentName = '';
      this.queryParam.endDate = '';
      this.getStockList()
    },
    async handleEdit(index, row) {
      await this.getMoudleList();
      await this.getStockDetail(row.id)
      this.moudleForm.moudleIdList = this.stockDetail.moudleList.map(item => {
        return item.id
      })
      console.log(this.moudleForm.moudleIdList)
      this.moudleDialog = true
      this.moudleForm.stockId = row.id
      this.editSystem = {

      }
    },
    handleAdd() {
      this.visible = true
      this.isEdit = false
      this.editSystem = {
        companyId: '',
        equipmentId: '',
        nature: '',
        parentId: '',
        remark: '',
        typeId: 1,
        version: 1,
        workproc: ''
      }
    },
    handleCloseDialog() {
      this.visible = !this.visible
    },
    handleSizeChange(val) {
      this.paging.pageSize = val
      this.getStockList()
    },
    handleCurrentChange(val) {
      this.paging.currentPage = val
      this.getStockList()
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/public.scss";
::v-deep .checkInput .el-form-item__content {
  display: flex;
}
::v-deep .moudleDialog .el-dialog__body {
  padding: 10px 20px;
  height: auto;
  background:#fff;
}
::v-deep .moudleDialog .el-dialog__footer{
  background:#fff;
}
::v-deep .moudleDialog .el-dialog__header {
  padding: 20px 20px 10px;
  height: 50px;
}
::v-deep .moudleDialog .el-dialog {
  width: 40%;
}
.el-icon-remove-outline::before {
  margin-right: 4px;
}
.pt {
  padding-top: 20px;
  > .el-select {
    width: 185px;
  }
}
.errorImg {
  display: inline-block;
  width: 60px;
  height: 60px;
}
.sys-input {
  width: 260px;
}
.icon-qingkong:before {
  margin-right: 4px;
}
</style>

